package com.dms.modules.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.utils.FileUploadUtils;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductCategory;
import com.dms.modules.product.service.ProductCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 商品分类控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/products/categories")
@Api(tags = "商品分类接口")
@RequiredArgsConstructor
@Validated
public class ProductCategoryController {

    private final ProductCategoryService categoryService;
    private final FileUploadUtils fileUploadUtils;

    @GetMapping
    @ApiOperation("获取所有分类")
    public ApiResponse<List<ProductCategory>> getAllCategories() {
        return ApiResponse.success(categoryService.list());
    }

    @GetMapping("/tree")
    @ApiOperation("获取分类树结构")
    public ApiResponse<List<ProductCategory>> getCategoryTree() {
        return ApiResponse.success(categoryService.getCategoryTree());
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID获取分类")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "分类ID", required = true, paramType = "path")
    })
    public ApiResponse<ProductCategory> getCategory(@PathVariable Long id) {
        return ApiResponse.success(categoryService.getById(id));
    }

    @GetMapping("/children/{parentId}")
    @ApiOperation("获取子分类")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "parentId", value = "父分类ID", required = true, paramType = "path")
    })
    public ApiResponse<List<ProductCategory>> getChildCategories(@PathVariable Long parentId) {
        LambdaQueryWrapper<ProductCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategory::getParentId, parentId);
        return ApiResponse.success(categoryService.list(wrapper));
    }

    @GetMapping("/page")
    @ApiOperation("分页获取分类")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1"),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10"),
        @ApiImplicitParam(name = "name", value = "分类名称", required = false)
    })
    public ApiResponse<Page<ProductCategory>> pageCategories(
            @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(1) Integer pageSize,
            @RequestParam(required = false) String name) {
        return ApiResponse.success(categoryService.pageCategories(pageNum, pageSize, name));
    }

    @PostMapping
    @ApiOperation("新增分类")
    @PreAuthorize("hasAnyRole('ADMIN', 'MERCHANT')")
    public ApiResponse<Boolean> addCategory(@RequestBody @Validated ProductCategory category) {
        return ApiResponse.success(categoryService.save(category));
    }

    @PutMapping("/{id}")
    @ApiOperation("更新分类")
    @PreAuthorize("hasAnyRole('ADMIN', 'MERCHANT')")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "分类ID", required = true, paramType = "path")
    })
    public ApiResponse<Boolean> updateCategory(
            @PathVariable @NotNull(message = "分类ID不能为空") Long id,
            @RequestBody @Validated ProductCategory category) {
        category.setId(id);
        return ApiResponse.success(categoryService.updateById(category));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除分类")
    @PreAuthorize("hasAnyRole('ADMIN', 'MERCHANT')")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "分类ID", required = true, paramType = "path")
    })
    public ApiResponse<Boolean> deleteCategory(@PathVariable @NotNull(message = "分类ID不能为空") Long id) {
        // 检查是否有子分类
        LambdaQueryWrapper<ProductCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategory::getParentId, id);
        long count = categoryService.count(wrapper);
        if (count > 0) {
            return ApiResponse.error("该分类下存在子分类，无法删除");
        }
        
        // 检查该分类下是否有商品
        if (categoryService.hasProducts(id)) {
            return ApiResponse.error("该分类下存在商品，无法删除");
        }
        
        return ApiResponse.success(categoryService.removeById(id));
    }

    @PutMapping("/{categoryId}/visible")
    @ApiOperation("更新分类显示状态")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> updateVisible(
            @ApiParam("分类ID") @PathVariable Long categoryId,
            @ApiParam("是否显示：0-不显示，1-显示") @RequestParam Integer visible) {
        log.info("更新分类显示状态: categoryId={}, visible={}", categoryId, visible);
        categoryService.updateVisible(categoryId, visible);
        return ApiResponse.success(null);
    }

    @PostMapping("/upload/image")
    @ApiOperation("上传分类图片")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<String> uploadCategoryImage(
            @ApiParam(value = "图片文件", required = true) 
            @RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ApiResponse.businessFailed("请选择要上传的文件");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ApiResponse.businessFailed("只能上传图片文件");
            }

            // 使用FileUploadUtils上传到OSS
            String imageUrl = fileUploadUtils.uploadFile(file, "category/images");
            return ApiResponse.success(imageUrl);
        } catch (Exception e) {
            log.error("上传分类图片失败", e);
            return ApiResponse.businessFailed("上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/dimension")
    @ApiOperation("获取次元分类")
    public ApiResponse<List<ProductCategory>> getDimensionCategories(
            @RequestParam String dimension) {
        log.info("获取次元分类: dimension={}", dimension);
        return ApiResponse.success(categoryService.getDimensionCategories(dimension));
    }

    @GetMapping("/list")
    @ApiOperation("获取分类列表")
    public ApiResponse<List<ProductCategory>> getCategoryList(
            @RequestParam(required = false) Long parentId) {
        log.info("获取分类列表: parentId={}", parentId);
        return ApiResponse.success(categoryService.getCategoryList(parentId));
    }

    @GetMapping("/{categoryId}/products")
    @ApiOperation("获取分类商品列表")
    public ApiResponse<IPage<Product>> getCategoryProducts(
            @PathVariable @NotNull(message = "分类ID不能为空") Long categoryId,
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        log.info("获取分类商品列表: categoryId={}, pageNum={}, pageSize={}", categoryId, pageNum, pageSize);
        try {
            IPage<Product> result = categoryService.getCategoryProducts(categoryId, pageNum, pageSize);
            log.info("获取分类商品列表成功: total={}, current={}, size={}", 
                    result.getTotal(), result.getCurrent(), result.getSize());
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取分类商品列表失败: categoryId={}, error={}", categoryId, e.getMessage(), e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

    @GetMapping("/products/filter")
    @ApiOperation("获取多级分类筛选商品列表")
    public ApiResponse<IPage<Product>> getFilteredProducts(
            @ApiParam("分类ID列表（按层级顺序）") @RequestParam List<Long> categoryIds,
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        log.info("获取多级分类筛选商品列表: categoryIds={}, pageNum={}, pageSize={}", categoryIds, pageNum, pageSize);
        try {
            IPage<Product> result = categoryService.getFilteredCategoryProducts(categoryIds, pageNum, pageSize);
            log.info("获取多级分类筛选商品列表成功: total={}, current={}, size={}", 
                    result.getTotal(), result.getCurrent(), result.getSize());
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取多级分类筛选商品列表失败: categoryIds={}, error={}", categoryIds, e.getMessage(), e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

} 